package com.supplychain.scm.core.feign.interceptor;


import com.supplychain.scm.core.basis.constant.StringPool;
import com.supplychain.scm.core.feign.constant.SupplyFeignConstants;
import com.supplychain.scm.core.basis.constant.CommonConstants;
import feign.RequestTemplate;
import feign.Target;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName AbstractSupplyFeignInterceptor
 * @Description feign拦截器
 * @createTime 11:50:00 2022/08/18
 */
public abstract class AbstractSupplyFeignInterceptor extends AbstractGrayFeignInterceptor {

    @Setter
    private String bizCode;

    private String version;

    public AbstractSupplyFeignInterceptor() {
        if (this.projectVersion.contains(StringPool.DASH)) {
            this.version = this.projectVersion.split(StringPool.DASH)[CommonConstants.ZERO];
        }
    }

    @Override
    public final void apply(RequestTemplate requestTemplate) {
        String applicationName = Optional.of(requestTemplate).map(RequestTemplate::feignTarget).map(Target::name).orElse(StringPool.EMPTY);
        if (StringUtils.isNotBlank(applicationName) && Objects.equals(this.applycationName(), applicationName)) {
            super.apply(requestTemplate);
            if (StringUtils.isNotBlank(this.bizCode)) {
                requestTemplate.header(SupplyFeignConstants.BIZ_CODE, this.bizCode);
            } else {
                requestTemplate.header(SupplyFeignConstants.BIZ_CODE, getDynamicBizCode(requestTemplate));
            }
            if (StringUtils.isNotBlank(this.version)) {
                requestTemplate.header(this.versionName(), this.version);
            }
        }
    }

    /**
     * 版本号请求头 key
     *
     * @return
     */
    protected abstract String versionName();

    /**
     * 提供获取bizCode的方法
     * 需要动态设置时子类重写
     * @param requestTemplate 传递RequestTemplate 防止上游服务通过body判断
     * @return
     */
    protected String getDynamicBizCode(RequestTemplate requestTemplate) {
        return StringPool.EMPTY;
    }
}
